package com.compression.tool.model.manager;

import com.compression.tool.model.enums.TaskStatus;
import com.compression.tool.model.task.CompressionTask;
import com.compression.tool.model.task.ProgressListener;

import javax.swing.*;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author 自然醒
 * @version 1.0
 */

// 任务管理器
public class TaskManager {
    private static TaskManager instance; //当前的任务实例
    private final ExecutorService executorService; //线程池服务
    private final Map<String, CompressionTask> tasks; //任务列表
    private final List<CompressionTask> taskHistory; //任务历史

    // 全局UI组件引用
    private JLabel globalStatusLabel;
    private JProgressBar globalProgressBar;
    private JTextArea taskLogArea;
    private JTable taskTable;


    /**
     * 重置单例实例（主要用于测试）
     * todo
     */
    public static synchronized void resetInstance() {
        if (instance != null) {
            instance.shutdown();
            instance = null;
        }
    }

    // 设置UI组件引用
    public void setGlobalUIComponents(JLabel statusLabel, JProgressBar progressBar,
                                      JTextArea logArea, JTable table) {
        this.globalStatusLabel = statusLabel;
        this.globalProgressBar = progressBar;
        this.taskLogArea = logArea;
        this.taskTable = table;
    }

    private TaskManager() {
        this.executorService = Executors.newFixedThreadPool(3); // 最大并发3个任务
        this.tasks = new ConcurrentHashMap<>();
        this.taskHistory = Collections.synchronizedList(new ArrayList<>());
    }

    //使用单例设计模式中的懒汉式获取到实例
    //保证了线程安全 不会出现阻塞等问题 但是可能会影响性能 因为每次获取实例时都会重新获取锁
    public static synchronized TaskManager getInstance() {
        if (instance == null) {
            instance = new TaskManager();
        }
        return instance;
    }

    // 提交新任务
    public String submitTask(CompressionTask task) {
        tasks.put(task.getTaskId(), task);
        taskHistory.add(task);
        //保持原有监听器
        ProgressListener exitingListener = task.getProgressListener();

        //创建组合监听器
        ProgressListener combinedListener = new ProgressListener() {
            @Override
            public void onProgressUpdate(double progress) {
                //调用原有监听器
                if(exitingListener != null){
                    exitingListener.onProgressUpdate(progress);
                }
                //更新全局任务监控界面
                updateGlobalTaskMonitor( progress);
            }

            @Override
            public void onStatusChange(TaskStatus status) {
                //调用原有监听器
                if(exitingListener != null){
                    exitingListener.onStatusChange(status);
                }
                //更新全局状态显示
                updateGlobalStatusDisplay(status);
            }

            @Override
            public void onTaskComplete(boolean success, String message) {
                //调用原有监听器
                if(exitingListener != null){
                    exitingListener.onTaskComplete(success, message);
                }
                //更新全局
                logTaskCompletion(success, message);
            }
        };

        //同时需要一个监听器进行对任务的状态监听
//        task.setProgressListener(createGlobalProgressListener());

        //设置组合监听器
        task.setProgressListener(combinedListener);


        executorService.submit(() -> {
            try{
                task.execute();
            }finally {
                tasks.remove(task.getTaskId());
            }
        });

        return task.getTaskId();
    }

    // 创建全局进度监听器
    private ProgressListener createGlobalProgressListener() {
        return new ProgressListener() {
            @Override
            public void onProgressUpdate(double progress) {
                updateGlobalTaskMonitor(progress);
            }

            @Override
            public void onStatusChange(TaskStatus status) {
                updateGlobalStatusDisplay(status);
            }

            @Override
            public void onTaskComplete(boolean success, String message) {
                logTaskCompletion(success, message);
            }
        };
    }


    // 更新全局任务监控界面
    private void updateGlobalTaskMonitor(double progress) {
        SwingUtilities.invokeLater(() -> {
            if (globalProgressBar != null) {
                globalProgressBar.setValue((int) progress);
            }

            // 计算并显示总体进度（所有任务的加权平均）
            double overallProgress = calculateOverallProgress();
            if (globalStatusLabel != null) {
                globalStatusLabel.setText(String.format("总体进度: %.1f%%", overallProgress));
            }
        });
    }

    // 计算总体进度（所有活动任务的加权平均）
    private double calculateOverallProgress() {
        if (tasks.isEmpty()) {
            return 0;
        }

        double totalWeightedProgress = 0;
        long totalBytes = 0;

        for (CompressionTask task : tasks.values()) {
            totalWeightedProgress += task.getProgress() * task.getTotalBytes();
            totalBytes += task.getTotalBytes();
        }

        return totalBytes > 0 ? totalWeightedProgress / totalBytes : 0;
    }

    // 更新全局状态显示
    private void updateGlobalStatusDisplay(TaskStatus status) {
        SwingUtilities.invokeLater(() -> {
            if (globalStatusLabel != null) {
                globalStatusLabel.setText("当前状态: " + status.toString());
            }
        });
    }

    // 记录任务完成日志
    private void logTaskCompletion(boolean success, String message) {
        SwingUtilities.invokeLater(() -> {
            if (taskLogArea != null) {
                String timestamp = new Date().toString();
                String result = success ? "成功" : "失败";
                taskLogArea.append(String.format("[%s] 任务%s: %s\n",
                        timestamp, result, message));

                // 自动滚动到最后
                try {
                    if (taskLogArea.getDocument() != null) {
                        taskLogArea.setCaretPosition(taskLogArea.getDocument().getLength());
                    }
                } catch (Exception e) {
                    // 忽略 UI 相关的异常，不影响核心功能
                    System.err.println("UI 操作异常: " + e.getMessage());
                }
            }
        });
    }

    // 获取所有活动任务
    public List<CompressionTask> getActiveTasks() {
        return new ArrayList<>(tasks.values());
    }

    // 获取任务历史
    public List<CompressionTask> getTaskHistory() {
        return new ArrayList<>(taskHistory);
    }

    // 根据ID获取任务
    public CompressionTask getTask(String taskId) {
        return tasks.get(taskId);
    }

    // 取消任务
    public boolean cancelTask(String taskId) {
        CompressionTask task = tasks.get(taskId);
        if (task != null) {
            task.cancel();
            return true;
        }
        return false;
    }

    // 暂停任务
    public boolean pauseTask(String taskId) {
        CompressionTask task = tasks.get(taskId);
        if (task != null && task.getStatus() == TaskStatus.RUNNING) {
            task.pause();
            return true;
        }
        return false;
    }

    // 恢复任务
    public boolean resumeTask(String taskId) {
        CompressionTask task = tasks.get(taskId);
        if (task != null && task.getStatus() == TaskStatus.PAUSED) {
            task.resume();
            return true;
        }
        return false;
    }

    // 获取系统负载信息
    public String getSystemLoadInfo() {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService;
        return String.format("活跃任务: %d, 队列任务: %d, 最大线程数: %d",
                executor.getActiveCount(),
                executor.getQueue().size(),
                executor.getMaximumPoolSize());
    }

    // 关闭任务管理器
    public void shutdown() {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
    }
}
